<template>
  <div class="min-h-screen bg-gray-50 py-12">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 步骤指示器 -->
      <UStepper
        v-model="currentStep"
        :steps="[
          { title: '填写反馈', icon: 'i-heroicons-pencil-square', complete: currentStep > 0 },
          { title: '提交中', icon: 'i-heroicons-arrow-path', complete: currentStep > 1 },
          { title: '提交完成', icon: 'i-heroicons-check-circle', complete: currentStep === 2 }
        ]"
        class="mb-8"
        :ui="{
          wrapper: 'relative',
          step: {
            complete: 'text-primary-600',
            active: 'text-primary-600 font-medium',
            inactive: 'text-gray-500'
          }
        }"
      />
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold text-gray-900">意见反馈</h1>
        <p class="mt-4 text-lg text-gray-600">您的反馈对我们很重要，帮助我们不断改进产品</p>
      </div>

      <!-- 反馈表单 -->
      <div class="bg-white rounded-xl shadow-lg p-8">
        <form @submit.prevent="handleSubmit" class="space-y-8">
          <!-- 反馈类型 -->
          <div>
            <label class="block text-base font-medium text-gray-700 mb-3">反馈类型</label>
            <div class="grid grid-cols-2 gap-8">
              <button
                v-for="type in feedbackTypes"
                :key="type.id"
                type="button"
                :class="[
                  'flex flex-col items-center p-8 rounded-lg border-2 transition-all duration-200',
                  selectedType === type.id
                    ? 'border-primary-500 bg-primary-50 text-primary-700 shadow-md'
                    : 'border-gray-200 hover:border-primary-200 hover:bg-gray-50 hover:shadow-md'
                ]"
                @click="selectedType = type.id"
              >
                <UIcon :name="type.icon" class="h-10 w-10 mb-4" />
                <span class="text-lg font-medium">{{ type.name }}</span>
              </button>
            </div>
          </div>

          <!-- 问题描述 -->
          <div>
            <label for="description" class="block text-sm font-medium text-gray-700 mb-2">
              问题描述
              <span class="text-red-500">*</span>
            </label>
            <textarea
              id="description"
              v-model="description"
              rows="4"
              class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500"
              placeholder="请详细描述您遇到的问题或建议..."
              required
            />
          </div>

          <!-- 图片上传 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">上传截图（可选）</label>
            <div
              class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-primary-500 transition-colors duration-200 cursor-pointer"
              @click="triggerFileInput"
              @dragover.prevent
              @drop.prevent="handleDrop"
            >
              <div class="space-y-2 text-center">
                <UIcon name="i-heroicons-photo" class="mx-auto h-12 w-12 text-gray-400" />
                <div class="text-sm text-gray-600">
                  <label class="relative cursor-pointer text-primary-600 hover:text-primary-500">
                    <span>点击上传图片</span>
                    <input
                      ref="fileInput"
                      type="file"
                      class="sr-only"
                      accept="image/*"
                      multiple
                      @change="handleFileChange"
                    />
                  </label>
                  <p class="text-gray-500">或将图片拖放到这里</p>
                </div>
                <p class="text-xs text-gray-500">PNG, JPG, GIF 格式，单个文件不超过 5MB</p>
              </div>
            </div>

            <!-- 预览图片 -->
            <div v-if="previewImages.length > 0" class="mt-4 grid grid-cols-3 gap-4">
              <div
                v-for="(image, index) in previewImages"
                :key="index"
                class="relative rounded-lg overflow-hidden group"
              >
                <img :src="image.url" class="w-full h-24 object-cover" />
                <button
                  type="button"
                  class="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                  @click="removeImage(index)"
                >
                  <UIcon name="i-heroicons-trash" class="h-6 w-6 text-white" />
                </button>
              </div>
            </div>
          </div>

          <!-- 联系方式 -->
          <div>
            <label for="contact" class="block text-sm font-medium text-gray-700 mb-2">联系方式（可选）</label>
            <input
              id="contact"
              v-model="contact"
              type="text"
              class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500"
              placeholder="请留下您的邮箱或手机号，方便我们回复您"
            />
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-center">
            <UButton
              type="submit"
              color="primary"
              size="xl"
              :loading="submitting"
              class="w-full sm:w-auto"
            >
              <template #leading>
                <UIcon name="i-heroicons-paper-airplane" />
              </template>
              提交反馈
            </UButton>
          </div>
        </form>
      </div>
    </div>

    <!-- 成功提示 -->
    <UModal v-model="showSuccessModal">
      <div class="p-6 text-center">
        <UIcon name="i-heroicons-check-circle" class="mx-auto h-16 w-16 text-green-500 mb-4" />
        <h3 class="text-lg font-medium text-gray-900 mb-2">反馈提交成功</h3>
        <p class="text-sm text-gray-500 mb-6">感谢您的反馈，我们会认真处理您的建议</p>
        <UButton color="primary" @click="showSuccessModal = false">确定</UButton>
      </div>
    </UModal>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { api } from '~/utils/api'

// 反馈类型
const feedbackTypes = [
  { id: 'suggestion', name: '功能建议', icon: 'i-heroicons-light-bulb' },
  { id: 'problem', name: '问题反馈', icon: 'i-heroicons-bug-ant' }
]

// 表单数据
const selectedType = ref('feature')
const description = ref('')
const contact = ref('')
const previewImages = ref<{ file: File; url: string }[]>([])
const fileInput = ref<HTMLInputElement | null>(null)

// 状态
const submitting = ref(false)
const showSuccessModal = ref(false)
const currentStep = ref(0)

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files) {
    addFiles(Array.from(input.files))
  }
}

// 处理拖放
const handleDrop = (event: DragEvent) => {
  const files = event.dataTransfer?.files
  if (files) {
    addFiles(Array.from(files))
  }
}

// 添加文件
const addFiles = (files: File[]) => {
  const imageFiles = files.filter(file => {
    const isImage = file.type.startsWith('image/')
    const isValidSize = file.size <= 5 * 1024 * 1024 // 5MB
    return isImage && isValidSize
  })

  imageFiles.forEach(file => {
    const reader = new FileReader()
    reader.onload = (e) => {
      previewImages.value.push({
        file,
        url: e.target?.result as string
      })
    }
    reader.readAsDataURL(file)
  })
}

// 移除图片
const removeImage = (index: number) => {
  previewImages.value.splice(index, 1)
}

// 提交表单
const handleSubmit = async () => {
  if (!description.value.trim()) {
    return
  }

  submitting.value = true
  currentStep.value = 1 // 更新为提交中状态

  try {
    // 创建请求数据
    const requestData = {
      feedback_type: selectedType.value,
      content: description.value
    }

    // 发送请求
    const response = await api.post('/api/v1/feedback', requestData)
    
    if (response.code === 0) {
      currentStep.value = 2 // 更新为提交完成状态
      
      // 重置表单
      selectedType.value = 'feature'
      description.value = ''
      contact.value = ''
      previewImages.value = []
      
      // 显示成功提示并延迟跳转
      showSuccessModal.value = true
      
      // 1.5秒后跳转到我的反馈页面
      setTimeout(() => {
        navigateTo('/user/my-feedback')
      }, 1500)
    }
  } catch (error) {
    console.error('提交反馈失败:', error)
  } finally {
    submitting.value = false
  }
}
</script>